<template>
    <div class="production-plan">
        <!-- 头部信息 -->
        <div class="header-info">
            <span>创建人：赵五六</span>
            <span>创建时间：2025-05-11 20:08:31</span>
            <span>最后修改人：赵五六</span>
            <span>修改时间：2022-06-07 19:49:12</span>
            <el-button type="primary" @click="printPage">打印</el-button>
            <el-button @click="restartProcess">重启</el-button>
        </div>
        <el-button @click="gotoWorkOrder">工单信息</el-button>
        <el-button @click="gotoReportWork">报工记录</el-button>

        <!-- 标签页 -->
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="操作记录" name="operation"></el-tab-pane>
        </el-tabs>

        <!-- 操作记录内容 -->
        <div v-if="activeTab === 'operation'" class="operation-record">
            <div style="margin-bottom: 15px">
                <el-button @click="exportData">导出</el-button>
                <el-input v-model="searchKey" placeholder="搜索操作人或内容" style="width: 240px; margin-left: 10px" clearable
                    suffix-icon="Search" />
            </div>

            <!-- 数据表格 -->
            <el-table :data="filteredRecords">
                <el-table-column label="操作人" prop="operationsName" width="120"></el-table-column>
                <el-table-column label="操作时间" prop="operationsStatus" width="180"></el-table-column>
                <el-table-column label="操作内容" prop="operationsAddress"></el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { DocumentRemove } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';
import { utils, writeFile } from 'xlsx'
const router = useRouter();

// 状态管理
const activeTab = ref('operation')
const searchKey = ref('')
const records = ref([])
const loading = ref(false)

// 过滤逻辑
const filteredRecords = computed(() => {
    const keyword = searchKey.value.toLowerCase()
    return records.value.filter(item =>
        (item.operationsName || '').toLowerCase().includes(keyword) ||
        (item.operationsAddress || '').toLowerCase().includes(keyword)
    )
})

// 文件下载工具
const downloadFile = (content, fileName, contentType) => {
    const a = document.createElement('a')
    const file = new Blob([content], { type: contentType })
    a.href = URL.createObjectURL(file)
    a.download = fileName
    a.click()
    URL.revokeObjectURL(a.href)
}

// 数据加载
const loadData = async () => {
    try {
        const res = await axios.get("https://localhost:7006/api/Process/OperationsQuser")
        records.value = res.data.data.map(item => ({
            operationsName: item.operationsName,
            operationsStatus: item.operationsStatus,
            operationsAddress: item.operationsAddress
        }))
    } catch (err) {
        console.error('加载失败:', err)
        ElMessage.error('数据加载失败')
    }
}

// 导出CSV
const exportData = () => {
    if (filteredRecords.value.length === 0) {
        ElMessage.warning('没有可导出的数据')
        return
    }

    try {
        // 转换数据格式
        const data = filteredRecords.value.map(item => ({
            操作人: item.operationsName,
            操作时间: item.operationsStatus,
            操作内容: item.operationsAddress
        }))

        // 创建工作簿
        const worksheet = utils.json_to_sheet(data)
        const workbook = utils.book_new()
        utils.book_append_sheet(workbook, worksheet, "操作记录")

        // 生成文件
        const date = new Date().toISOString().slice(0, 10)
        writeFile(workbook, `操作记录_${date}.xlsx`)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
    }
}

// 打印功能
const printPage = () => {
    const printContent = document.querySelector('.operation-record').cloneNode(true)
    const printWindow = window.open('', '_blank')

    printWindow.document.write(`
        <html>
            <head>
                <title>操作记录打印</title>
                <style>
                    body { margin: 20px; font-family: 'Microsoft YaHei' }
                    table { width: 100%; border-collapse: collapse }
                    th, td { 
                        border: 1px solid #ddd; 
                        padding: 8px;
                        text-align: left 
                    }
                    th { background-color: #f5f7fa }
                    .el-table__header { display: table-header-group; }
                </style>
            </head>
            <body>
                ${printContent.outerHTML}
            </body>
        </html>
    `)

    printWindow.document.close()
    printWindow.print()
    printWindow.close()
}

// 路由跳转
const gotoWorkOrder = () => router.push('/NewproductionworkorderShowView')
const gotoReportWork = () => router.push('/WorkOrderDetailInformation')

// 初始化
onMounted(loadData)
</script>

<style scoped>
.production-plan {
    padding: 20px;
    height: 100vh;
}

.header-info span {
    margin-right: 25px;
    font-size: 14px;
    color: #666;
}

.operation-record {
    margin-top: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

@media print {

    .el-button,
    .el-tabs__header,
    .header-info>span:last-child,
    .el-input {
        display: none !important;
    }

    .operation-record {
        margin: 0;
        padding: 0;
        box-shadow: none;
    }

    .el-table {
        width: 100% !important;
        font-size: 12px;
    }

    table {
        page-break-inside: auto;
    }

    tr {
        page-break-inside: avoid;
    }
}

@page {
    size: auto;
    margin: 10mm;
}
</style>